﻿Imports AutoMapper
Imports FTTK.Exceptions
Imports FTTK.Services.EventArgs
Imports FTTK.Entities
Imports FTTK.Services.Interfaces
Imports FTTK.Utilities
Imports System.Net
Imports FTTK.Json
Imports System.Diagnostics.Contracts
Imports System.Text

Namespace FTTK.Services.Implementations.Rest
    ''' <summary>
    ''' Provides services relating to a partner account
    ''' </summary>
    ''' <remarks></remarks>
    Public Class PartnerService
        Inherits BaseService
        Implements IPartnerService

        Shared Sub New()
            Try
                PartnerServiceMapping.DefineMapping()
            Catch ex As Exception

            End Try
        End Sub


        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <param name="apiKey">The API key.</param>
        ''' <param name="cacheAdapter">The cache adapter.</param>
        ''' <remarks></remarks>
        Public Sub New(apiKey As String, cacheAdapter As ICacheAdapter)
            MyBase.New(apiKey, cacheAdapter)
        End Sub


        ''' <summary>
        ''' Initializes a new instance of the <see cref="PartnerService" /> class.
        ''' </summary>
        ''' <param name="apiKey">The API key.</param>
        ''' <remarks></remarks>
        Public Sub New(apiKey As String)
            MyBase.New(apiKey)
        End Sub

#Region "GetRepresentativeCategories"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Gets the representative categories.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent (null for first level categories).</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetRepresentativeCategories(ByVal languageId As Integer,
                                                    Optional ByVal idCategoryParent As Integer? = Nothing) As IEnumerable(Of Category) Implements IPartnerService.GetRepresentativeCategories
            Dim retVal As IEnumerable(Of Category) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Category))("GetRepresentativeCategories",
                                                      Function()
                                                          Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetRepresentativeCategoriesUrl(languageId, idCategoryParent))
                                                          Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                          Return result
                                                      End Function,
                                                      RequestUrlHelper.GetRepresentativeCategoriesUrl(languageId, idCategoryParent))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Gets the categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetRepresentativeCategoriesAsync(ByVal languageId As Integer,
                                                    ByVal idCategoryParent As Integer,
                                                    ByVal userState As Object) Implements IPartnerService.GetRepresentativeCategoriesAsync
            GetRepresentativeCategoriesAsync(languageId, idCategoryParent, userState)
        End Sub

        ''' <summary>
        ''' Gets the categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetRepresentativeCategoriesAsync(ByVal languageId As Integer,
                                                    ByVal userState As Object) Implements IPartnerService.GetRepresentativeCategoriesAsync
            GetRepresentativeCategoriesAsync(languageId, CType(Nothing, Integer?), userState)
        End Sub

        Private Sub GetRepresentativeCategoriesAsync(ByVal languageId As Integer,
                                                     ByVal idCategoryParent As Integer?,
                                                     ByVal userState As Object)
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Category))("GetRepresentativeCategories",
                                                                             RequestUrlHelper.GetRepresentativeCategoriesUrl(languageId, idCategoryParent))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetRepresentativeCategoriesUrl(languageId, idCategoryParent),
                                                   AddressOf GetRepresentativeCategoriesAsyncCallback,
                                                   New Tuple(Of Integer, Integer?, Object)(languageId, idCategoryParent, userState))
                Else
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                                     .Result = True,
                                                                                                                     .Categories = result,
                                                                                                                     .UserState = userState,
                                                                                                                     .LanguageId = languageId,
                                                                                                                     .CategoryParentId = idCategoryParent})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                                     .Result = False,
                                                                                                                     .Categories = Nothing,
                                                                                                                     .UserState = userState,
                                                                                                                     .LanguageId = languageId,
                                                                                                                     .CategoryParentId = idCategoryParent})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetRepresentativeCategoriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Integer?, Object))
            If ex Is Nothing Then
                Dim arg As GetRepresentativeCategoriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, IEnumerable(Of Category))(result)
                    SetResultInCache(Of IEnumerable(Of Category))("GetRepresentativeCategories", RequestUrlHelper.GetRepresentativeCategoriesUrl(userTuple.Item1, userTuple.Item2), retval)
                    arg = New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item3, .Result = True,
                                                                        .Categories = retval, .CategoryParentId = userTuple.Item2, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item3, .Result = False, .Categories = Nothing,
                                                                                    .LanguageId = userTuple.Item1, .CategoryParentId = userTuple.Item2}

                End If
                OnGetRepresentativeCategoriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetRepresentativeCategoriesCompleted(New GetRepresentativeCategoriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                                    .Result = False, .UserState = userTuple.Item3,
                                                                                                                     .Categories = Nothing, .LanguageId = userTuple.Item1,
                                                                                                                     .CategoryParentId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Public Event GetRepresentativeCategoriesCompleted(ByVal sender As Object, ByVal e As GetRepresentativeCategoriesCompletedEventArgs) Implements IPartnerService.GetRepresentativeCategoriesCompleted

        Protected Sub OnGetRepresentativeCategoriesCompleted(ByVal e As EventArgs.GetRepresentativeCategoriesCompletedEventArgs)
            RaiseEvent GetRepresentativeCategoriesCompleted(Me, e)
        End Sub
#End Region

#Region "GetConceptualCategories"

#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Gets the conceptual categories.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent (null for first level categories).</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetConceptualCategories(ByVal languageId As Integer,
                                                Optional ByVal idCategoryParent As Integer? = Nothing) As IEnumerable(Of Category) Implements IPartnerService.GetConceptualCategories
            Dim retVal As IEnumerable(Of Category) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Category))("GetConceptualCategories",
                                                      Function()
                                                          Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetConceptualCategoriesUrl(languageId, idCategoryParent))
                                                          Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                          Return result
                                                      End Function,
                                                      RequestUrlHelper.GetConceptualCategoriesUrl(languageId, idCategoryParent))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Gets the conceptual categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="idCategoryParent">The id category parent.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetConceptualCategoriesAsync(ByVal languageId As Integer,
                                                ByVal idCategoryParent As Integer,
                                                ByVal userState As Object) Implements IPartnerService.GetConceptualCategoriesAsync
            GetRepresentativeCategoriesAsync(languageId, idCategoryParent, userState)
        End Sub

        ''' <summary>
        ''' Gets the conceptual categories async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">State of the user.</param>
        ''' <remarks></remarks>
        Public Sub GetConceptualCategoriesAsync(ByVal languageId As Integer,
                                                ByVal userState As Object) Implements IPartnerService.GetConceptualCategoriesAsync
            GetRepresentativeCategoriesAsync(languageId, CType(Nothing, Integer?), userState)
        End Sub

        Private Sub GetConceptualCategoriesAsync(ByVal languageId As Integer,
                                                     ByVal idCategoryParent As Integer?,
                                                     ByVal userState As Object)
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Category))("GetConceptualCategories",
                                                                             RequestUrlHelper.GetConceptualCategoriesUrl(languageId, idCategoryParent))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetConceptualCategoriesUrl(languageId, idCategoryParent),
                                                   AddressOf GetConceptualCategoriesAsyncCallback,
                                                   New Tuple(Of Integer, Integer?, Object)(languageId, idCategoryParent, userState))
                Else
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                            .Result = True,
                                                                                                            .Categories = result,
                                                                                                            .UserState = userState,
                                                                                                            .LanguageId = languageId,
                                                                                                            .CategoryParentId = idCategoryParent})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                            .Result = False,
                                                                                                            .Categories = Nothing,
                                                                                                            .UserState = userState,
                                                                                                            .LanguageId = languageId,
                                                                                                            .CategoryParentId = idCategoryParent})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetConceptualCategoriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Integer?, Object))
            If ex Is Nothing Then
                Dim arg As GetConceptualCategoriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, IEnumerable(Of Category))(result)
                    SetResultInCache(Of IEnumerable(Of Category))("GetConceptualCategories", RequestUrlHelper.GetConceptualCategoriesUrl(userTuple.Item1, userTuple.Item2), retval)
                    arg = New GetConceptualCategoriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item3, .Result = True,
                                                                        .Categories = retval, .CategoryParentId = userTuple.Item2, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetConceptualCategoriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item3, .Result = False, .Categories = Nothing,
                                                                                    .LanguageId = userTuple.Item1, .CategoryParentId = userTuple.Item2}

                End If
                OnGetConceptualCategoriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetConceptualCategoriesCompleted(New GetConceptualCategoriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                                    .Result = False, .UserState = userTuple.Item3,
                                                                                                                     .Categories = Nothing, .LanguageId = userTuple.Item1,
                                                                                                                     .CategoryParentId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetConceptualCategoriesCompleted(ByVal e As EventArgs.GetConceptualCategoriesCompletedEventArgs)
            RaiseEvent GetConceptualCategoriesCompleted(Me, e)
        End Sub

        Public Event GetConceptualCategoriesCompleted(ByVal sender As Object, ByVal e As GetConceptualCategoriesCompletedEventArgs) Implements IPartnerService.GetConceptualCategoriesCompleted
#End Region

#Region "GetTags"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method returns most searched tag and most used tag on fotolia website. 
        ''' This method may help you to create a tags cloud. 
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="tagType">Type of the tag:
        ''' <see cref="Fttk.Entities.TagType.Used">TagType.Used</see> : Most used tags to index media
        ''' <see cref="Fttk.Entities.TagType.Searched">TagType.Searched</see> : Most used tags to search for media
        ''' </param>
        ''' <remarks></remarks>
        Public Function GetTags(ByVal languageId As Integer, ByVal tagType As TagType) As IEnumerable(Of Tag) Implements IPartnerService.GetTags
            Dim retVal As IEnumerable(Of Tag) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Tag))("GetTags",
                                                      Function()
                                                          Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetTagsUrl(languageId, tagType))
                                                          Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                          Return result
                                                      End Function,
                                                      RequestUrlHelper.GetTagsUrl(languageId, tagType))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' This method returns most searched tag and most used tag on fotolia website ion async mode. 
        ''' This method may help you to create a tags cloud. 
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="tagType">The type of tag searched ("Used" o "Searched"). 
        ''' Used : Most used tags to index media
        ''' Searched : Most used tags to search for media
        ''' </param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetTagsAsync(ByVal languageId As Integer, ByVal tagType As TagType, ByVal userState As Object) Implements IPartnerService.GetTagsAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Tag))("GetTags",
                                                                             RequestUrlHelper.GetTagsUrl(languageId, tagType))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetTagsUrl(languageId, tagType),
                                                   AddressOf GetTagsAsyncCallback,
                                                   New Tuple(Of Integer, TagType, Object)(languageId, tagType, userState))
                Else
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = Nothing,
                                                                             .Result = True,
                                                                             .Tags = result,
                                                                             .UserState = userState,
                                                                             .LanguageId = languageId,
                                                                             .Type = tagType})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False,
                                                                            .Tags = Nothing,
                                                                            .UserState = userState,
                                                                            .LanguageId = languageId,
                                                                            .Type = tagType})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetTagsAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, TagType, Object))
            If ex Is Nothing Then
                Dim arg As GetTagsCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Tag))(result)
                    SetResultInCache(Of IEnumerable(Of Tag))("GetTags", RequestUrlHelper.GetTagsUrl(userTuple.Item1, userTuple.Item2), retval)
                    arg = New GetTagsCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item3, .Result = True,
                                                                .Tags = retval, .Type = userTuple.Item2, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetTagsCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item3, .Result = False, .Tags = Nothing,
                                                                                    .LanguageId = userTuple.Item1, .Type = userTuple.Item2}

                End If
                OnGetTagsCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetTagsCompleted(New GetTagsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False, .UserState = userTuple.Item3,
                                                                                .Tags = Nothing, .LanguageId = userTuple.Item1,
                                                                                .Type = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetTagsCompleted(ByVal e As EventArgs.GetTagsCompletedEventArgs)
            RaiseEvent GetTagsCompleted(Me, e)
        End Sub

        Public Event GetTagsCompleted(ByVal sender As Object, ByVal e As GetTagsCompletedEventArgs) Implements IPartnerService.GetTagsCompleted
#End Region

#Region "GetGalleries"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods returns public galleries for a defined language 
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="thumbnailSize">Gallery thumbnail size.</param>
        ''' <remarks></remarks>
        Public Function GetGalleries(ByVal languageId As Integer, thumbnailSize As GalleryThumbnailSize) As IEnumerable(Of Gallery) Implements IPartnerService.GetGalleries
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetGalleries",
                                                                  Function()
                                                                      Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetGalleriesUrl(languageId, thumbnailSize))
                                                                      Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                                      Return result
                                                                  End Function,
                                                                  RequestUrlHelper.GetGalleriesUrl(languageId, thumbnailSize))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods returns public galleries for a defined language in async mode.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="thumbnailSize">Gallery thumbnail size.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetGalleriesAsync(ByVal languageId As Integer, thumbnailSize As GalleryThumbnailSize, ByVal userState As Object) Implements IPartnerService.GetGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetGalleries",
                                                                             RequestUrlHelper.GetGalleriesUrl(languageId, thumbnailSize))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetGalleriesUrl(languageId, thumbnailSize),
                                                   AddressOf GetGalleriesAsyncCallback,
                                                   New Tuple(Of Integer, GalleryThumbnailSize, Object)(languageId, thumbnailSize, userState))
                Else
                    OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                             .Result = True,
                                                                             .Galleries = result,
                                                                             .UserState = userState,
                                                                             .LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False,
                                                                            .Galleries = Nothing,
                                                                            .UserState = userState,
                                                                            .LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetGalleriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, GalleryThumbnailSize, Object))
            If ex Is Nothing Then
                Dim arg As GetGalleriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Gallery))(result)
                    SetResultInCache(Of IEnumerable(Of Gallery))("GetGalleries", RequestUrlHelper.GetGalleriesUrl(userTuple.Item1, userTuple.Item2), retval)
                    arg = New GetGalleriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item3, .Result = True,
                                                                .Galleries = retval, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetGalleriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item3, .Result = False, .Galleries = Nothing,
                                                                                    .LanguageId = userTuple.Item1}

                End If
                OnGetGalleriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetGalleriesCompleted(New GetGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False, .UserState = userTuple.Item3,
                                                                                .Galleries = Nothing, .LanguageId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetGalleriesCompleted(ByVal e As EventArgs.GetGalleriesCompletedEventArgs)
            RaiseEvent GetGalleriesCompleted(Me, e)
        End Sub

        ''' <summary>
        ''' Occurs when GetGalleriesAsync completed.
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetGalleriesCompleted(ByVal sender As Object, ByVal e As GetGalleriesCompletedEventArgs) Implements IPartnerService.GetGalleriesCompleted

#End Region

#Region "GetSeasonalGalleries"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods returns public galleries for a defined language.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="thumbnailSize">Gallery Thumbnail size.</param>
        ''' <param name="themeId">ThemeId if you would like data for a specific ThemeId.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetSeasonalGalleries(ByVal languageId As Integer, ByVal thumbnailSize As GalleryThumbnailSize, ByVal themeId As Integer?) As IEnumerable(Of GalleryTheme) Implements IPartnerService.GetSeasonalGalleries
            Dim retVal As IEnumerable(Of GalleryTheme) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of GalleryTheme))("GetSeasonalGalleries",
                                                                      Function()
                                                                          Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetSeasonalGalleriesUrl(languageId, thumbnailSize, themeId))
                                                                          Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                                          Return result
                                                                      End Function,
                                                                      RequestUrlHelper.GetSeasonalGalleriesUrl(languageId, thumbnailSize, themeId))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' This methods returns public galleries for a defined language in async mode.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="thumbnailSize">Gallery Thumbnail size.</param>
        ''' <param name="themeId">ThemeId if you would like data for a specific ThemeId.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetSeasonalGalleriesAsync(ByVal languageId As Integer, ByVal thumbnailSize As GalleryThumbnailSize, ByVal themeId As Integer?, ByVal userState As Object) Implements IPartnerService.GetSeasonalGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of GalleryTheme))("GetSeasonalGalleries",
                                                                        RequestUrlHelper.GetSeasonalGalleriesUrl(languageId, thumbnailSize, themeId))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetSeasonalGalleriesUrl(languageId, thumbnailSize, themeId),
                                                   AddressOf GetSeasonalGalleriesAsyncCallback,
                                                   New Tuple(Of Integer, GalleryThumbnailSize, Integer?, Object)(languageId, thumbnailSize, themeId, userState))
                Else
                    OnGetSeasonalGalleriesCompleted(New GetSeasonalGalleriesCompletedEventArgs() With {.Error = Nothing, .Result = True, .GalleryThemes = result,
                                                                                                        .UserState = userState, .LanguageId = languageId, .ThemeId = themeId,
                                                                                                       .ThumbnailSize = thumbnailSize})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSeasonalGalleriesCompleted(New GetSeasonalGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx), .Result = False,
                                                                                                        .GalleryThemes = Nothing, .UserState = userState, .LanguageId = languageId,
                                                                                                       .ThemeId = themeId, .ThumbnailSize = thumbnailSize})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetSeasonalGalleriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, GalleryThumbnailSize, Integer?, Object))
            If ex Is Nothing Then
                Dim arg As GetSeasonalGalleriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of GalleryTheme))(result)
                    SetResultInCache(Of IEnumerable(Of GalleryTheme))("GetSeasonalGalleries", RequestUrlHelper.GetSeasonalGalleriesUrl(userTuple.Item1, userTuple.Item2, userTuple.Item3), retval)
                    arg = New GetSeasonalGalleriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item4, .Result = True,
                                                                             .GalleryThemes = retval, .LanguageId = userTuple.Item1, .ThumbnailSize = userTuple.Item2,
                                                                             .ThemeId = userTuple.Item3}
                Else
                    arg = New GetSeasonalGalleriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                                          .UserState = userTuple.Item4, .Result = False, .GalleryThemes = Nothing,
                                                                                                          .LanguageId = userTuple.Item1, .ThumbnailSize = userTuple.Item2,
                                                                                                          .ThemeId = userTuple.Item3}

                End If
                OnGetSeasonalGalleriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSeasonalGalleriesCompleted(New GetSeasonalGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx), .Result = False,
                                                                                                       .UserState = userTuple.Item4, .GalleryThemes = Nothing,
                                                                                                       .LanguageId = userTuple.Item1, .ThumbnailSize = userTuple.Item2,
                                                                                                       .ThemeId = userTuple.Item3})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetSeasonalGalleriesCompleted(ByVal e As EventArgs.GetSeasonalGalleriesCompletedEventArgs)
            RaiseEvent GetSeasonalGalleriesCompleted(Me, e)
        End Sub

        ''' <summary>
        ''' Occurs when GetSeasonalGalleriesAsync completed.
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetSeasonalGalleriesCompleted(ByVal sender As Object, ByVal e As GetSeasonalGalleriesCompletedEventArgs) Implements IPartnerService.GetSeasonalGalleriesCompleted

#End Region

#Region "GetCountries"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method returns Fotolia list of countries. 
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetCountries(ByVal languageId As Integer) As IEnumerable(Of Country) Implements IPartnerService.GetCountries
            Dim retVal As IEnumerable(Of Country) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Country))("GetCountries",
                                                                  Function()
                                                                      Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetCountriesUrl(languageId))
                                                                      Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                                      Return result
                                                                  End Function,
                                                                  RequestUrlHelper.GetCountriesUrl(languageId))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This method returns Fotolia list of countries in async mode. 
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">User state.</param>
        ''' <remarks></remarks>
        Public Sub GetCountriesAsync(ByVal languageId As Integer, ByVal userState As Object) Implements IPartnerService.GetCountriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Country))("GetCountries",
                                                                        RequestUrlHelper.GetCountriesUrl(languageId))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetCountriesUrl(languageId),
                                                   AddressOf GetCountriesAsyncCallback,
                                                   New Tuple(Of Integer, Object)(languageId, userState))
                Else
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = Nothing,
                                                                             .Result = True,
                                                                             .Countries = result,
                                                                             .UserState = userState,
                                                                             .LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False,
                                                                            .Countries = Nothing,
                                                                            .UserState = userState,
                                                                            .LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetCountriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Object))
            If ex Is Nothing Then
                Dim arg As GetCountriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Country))(result)
                    SetResultInCache(Of IEnumerable(Of Country))("GetCountries", RequestUrlHelper.GetCountriesUrl(userTuple.Item1), retval)
                    arg = New GetCountriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                .Countries = retval, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetCountriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item2, .Result = False, .Countries = Nothing,
                                                                                    .LanguageId = userTuple.Item1}

                End If
                OnGetCountriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetCountriesCompleted(New GetCountriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False, .UserState = userTuple.Item2,
                                                                                .Countries = Nothing, .LanguageId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetCountriesCompleted(ByVal e As EventArgs.GetCountriesCompletedEventArgs)
            RaiseEvent GetCountriesCompleted(Me, e)
        End Sub

        Public Event GetCountriesCompleted(ByVal sender As Object, ByVal e As GetCountriesCompletedEventArgs) Implements IPartnerService.GetCountriesCompleted
#End Region

#Region "GetSearchResult"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="numberOfResults">Total number of media that verify search parameters.</param>
        ''' <param name="columns">The desires columns in results collection.</param>
        ''' <param name="useCache">If true the method use cache, otherwise not use cache. Default is false.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetSearchResults(ByVal request As Entities.SearchRequest,
                                         ByRef numberOfResults As Integer,
                                         Optional columns As SearchResultsColumns = SearchResultsColumns.Base,
                                         Optional useCache As Boolean = False) As IEnumerable(Of Media) Implements IPartnerService.GetSearchResults
            Dim retVal As IEnumerable(Of Media) = Nothing
            Try
                If useCache Then
                    Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults",
                                                                                                     RequestUrlHelper.GetSearchResultsUrl(request, columns))
                    If cacheValue IsNot Nothing Then
                        retVal = cacheValue.Item1
                        numberOfResults = cacheValue.Item2
                    End If
                End If

                If retVal Is Nothing Then
                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetSearchResultsUrl(request, columns))
                    Dim completeResult = _JsonParser.ParseIntoSingleObject(resultStr)
                    numberOfResults = completeResult.GetValue(Of Integer)("nb_results", -1)
                    Dim mediaJsonObjects = From v In completeResult.Values.OfType(Of JsonObject)()
                                            Select v

                    retVal = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Media))(mediaJsonObjects).ToList()

                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults",
                                                                                  RequestUrlHelper.GetSearchResultsUrl(request, columns),
                                                                                  New Tuple(Of IEnumerable(Of Media), Integer)(retVal, numberOfResults))
                End If

            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="userState">User state.</param>
        ''' <param name="usecache">If true the method use cache, otherwise not use cache. Default is false.</param>
        ''' <remarks></remarks>
        Public Sub GetSearchResultsAsync(ByVal request As SearchRequest,
                                         ByVal userState As Object,
                                         Optional ByVal usecache As Boolean = False) Implements IPartnerService.GetSearchResultsAsync
            GetSearchResultsAsync(request, SearchResultsColumns.Base, userState, usecache)
        End Sub

        ''' <summary>
        ''' This methods makes possible to search media in fotolia image bank. Full search capabilities are available through the API.
        ''' </summary>
        ''' <param name="request">The search request.</param>
        ''' <param name="columns">The desires columns in results collection.</param>
        ''' <param name="userState">user state.</param>
        ''' <param name="usecache">If true the method use cache, otherwise not use cache. Default is false.</param>
        ''' <remarks></remarks>
        Public Sub GetSearchResultsAsync(ByVal request As SearchRequest,
                                         ByVal columns As SearchResultsColumns,
                                         ByVal userState As Object,
                                         Optional ByVal usecache As Boolean = False) Implements IPartnerService.GetSearchResultsAsync
            Try
                Dim result As IEnumerable(Of Media) = Nothing
                Dim numberOfResults As Integer
                If usecache Then
                    Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults",
                                                                                                     RequestUrlHelper.GetSearchResultsUrl(request, columns))
                    If cacheValue IsNot Nothing Then
                        result = cacheValue.Item1
                        numberOfResults = cacheValue.Item2
                    End If
                End If
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetSearchResultsUrl(request, columns),
                                                   AddressOf GetSearchResultsAsyncCallback,
                                                   New Tuple(Of SearchRequest, SearchResultsColumns, Object)(request, columns, userState))
                Else
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = Nothing,
                                                                                               .Result = True,
                                                                                               .MediaList = result,
                                                                                               .UserState = userState,
                                                                                               .NumberOfResults = numberOfResults,
                                                                                               .Request = request,
                                                                                               .Columns = columns})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                               .Result = False,
                                                                                               .MediaList = Nothing,
                                                                                               .UserState = userState,
                                                                                               .NumberOfResults = -1,
                                                                                               .Request = request,
                                                                                               .Columns = columns})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetSearchResultsAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of SearchRequest, SearchResultsColumns, Object))
            If ex Is Nothing Then
                Dim arg As GetSearchResultsCompletedEventArgs

                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim numberOfResults = result.GetValue(Of Integer)("nb_results", -1)
                    Dim mediaJsonObjects = From v In result.Values.OfType(Of JsonObject)()
                                            Select v

                    Dim mediaList = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Media))(mediaJsonObjects)

                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetSearchResults",
                                                                                  RequestUrlHelper.GetSearchResultsUrl(userTuple.Item1, userTuple.Item2),
                                                                                  New Tuple(Of IEnumerable(Of Media), Integer)(mediaList, numberOfResults))

                    arg = New GetSearchResultsCompletedEventArgs() With {.Error = Nothing,
                                                                        .Result = True,
                                                                        .MediaList = mediaList,
                                                                        .UserState = userTuple.Item3,
                                                                        .NumberOfResults = numberOfResults,
                                                                        .Request = userTuple.Item1,
                                                                        .Columns = userTuple.Item2}
                Else
                    arg = New GetSearchResultsCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item2, .Result = False, .MediaList = Nothing,
                                                                                    .NumberOfResults = -1, .Request = userTuple.Item1, .Columns = userTuple.Item2}

                End If
                OnGetSearchResultsCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSearchResultsCompleted(New GetSearchResultsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                               .Result = False,
                                                                                               .MediaList = Nothing,
                                                                                               .UserState = userTuple.Item3,
                                                                                               .NumberOfResults = -1,
                                                                                               .Request = userTuple.Item1,
                                                                                               .Columns = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetSearchResultsCompleted(ByVal e As EventArgs.GetSearchResultsCompletedEventArgs)
            RaiseEvent GetSearchResultsCompleted(Me, e)
        End Sub

        Public Event GetSearchResultsCompleted(ByVal sender As Object, ByVal e As GetSearchResultsCompletedEventArgs) Implements IPartnerService.GetSearchResultsCompleted
#End Region

#Region "GetMediaData"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method return all information about a media.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaData(ByVal mediaId As Integer,
                                     ByVal languageId As Integer,
                                     ByVal thumbnailSize As SearchThumbnailSize) As Media Implements IPartnerService.GetMediaData
            Dim retVal As Media = Nothing
            Try
                retVal = ExecuteQuery(Of Media)("GetMediaData",
                                                Function()
                                                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetMediaDataUrl(mediaId, languageId, thumbnailSize))
                                                    Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                    Return result
                                                End Function,
                                                RequestUrlHelper.GetMediaDataUrl(mediaId, languageId, thumbnailSize))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This method return all information about a media in async mode.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaDataAsync(ByVal mediaId As Integer,
                                     ByVal languageId As Integer,
                                     ByVal thumbnailSize As SearchThumbnailSize,
                                     ByVal userState As Object) Implements IPartnerService.GetMediaDataAsync
            Try
                Dim result = GetResultFromCache(Of Media)("GetMediaData",
                                                                        RequestUrlHelper.GetMediaDataUrl(mediaId, languageId, thumbnailSize))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetMediaDataUrl(mediaId, languageId, thumbnailSize),
                                                   AddressOf GetMediaDataAsyncCallback,
                                                   New Tuple(Of Integer, Integer, SearchThumbnailSize, Object)(mediaId, languageId, thumbnailSize, userState))
                Else
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = Nothing,
                                                                             .Result = True,
                                                                             .Media = result,
                                                                             .UserState = userState,
                                                                             .MediaId = mediaId,
                                                                             .ThumbnailSize = thumbnailSize,
                                                                             .LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                            .Result = False,
                                                                            .Media = Nothing,
                                                                            .UserState = userState,
                                                                            .MediaId = mediaId,
                                                                            .ThumbnailSize = thumbnailSize,
                                                                            .LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaDataAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Integer, SearchThumbnailSize, Object))
            If ex Is Nothing Then
                Dim arg As GetMediaDataCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, Media)(result)
                    SetResultInCache(Of Media)("GetMediaData", RequestUrlHelper.GetMediaDataUrl(userTuple.Item1, userTuple.Item2, userTuple.Item3), retval)
                    arg = New GetMediaDataCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item4, .Result = True,
                                                                .Media = retval, .MediaId = userTuple.Item1, .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3}
                Else
                    arg = New GetMediaDataCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                                    .UserState = userTuple.Item4, .Result = False,
                                                                                    .Media = Nothing, .MediaId = userTuple.Item1,
                                                                                    .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3}

                End If
                OnGetMediaDataCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaDataCompleted(New GetMediaDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .UserState = userTuple.Item4, .Result = False,
                                                                                    .Media = Nothing, .MediaId = userTuple.Item1,
                                                                                    .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetMediaDataCompleted(ByVal e As EventArgs.GetMediaDataCompletedEventArgs)
            RaiseEvent GetMediaDataCompleted(Me, e)
        End Sub

        ''' <summary>
        ''' Occurs when [get media data completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetMediaDataCompleted(ByVal sender As Object, ByVal e As GetMediaDataCompletedEventArgs) Implements IPartnerService.GetMediaDataCompleted
#End Region

#Region "GetBulkMediaData"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method return all information about a media.
        ''' </summary>
        ''' <param name="mediaIds">List of media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetBulkMediaData(ByVal mediaIds As IEnumerable(Of Integer), ByVal languageId As Integer, ByVal thumbnailSize As SearchThumbnailSize) As IEnumerable(Of Media) Implements IPartnerService.GetBulkMediaData
            Dim retVal As IEnumerable(Of Media) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Media))("GetBulkMediaData",
                                                                Function()
                                                                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetBulkMediaDataUrl(mediaIds, languageId, thumbnailSize))
                                                                    Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                                    Return result
                                                                End Function,
                                                                RequestUrlHelper.GetBulkMediaDataUrl(mediaIds, languageId, thumbnailSize),
                                                                Nothing,
                                                                 Function(jsonObj)
                                                                     If jsonObj Is Nothing Then Return Nothing
                                                                     Return (From k In jsonObj.Keys
                                                                            Where TypeOf jsonObj(k) Is JsonObject
                                                                            Select Mapper.Map(Of JsonObject, Media)(CType(jsonObj(k), JsonObject))).ToList()
                                                                 End Function)
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function

        ''' <summary>
        ''' This method return all information about a media.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetBulkMediaData(ByVal mediaId As Integer, ByVal languageId As Integer, ByVal thumbnailSize As SearchThumbnailSize) As Media Implements IPartnerService.GetBulkMediaData
            Return GetBulkMediaData({mediaId}, languageId, thumbnailSize).FirstOrDefault()
        End Function
#End If
        ''' <summary>
        ''' This method return all information about a media in async mode.
        ''' </summary>
        ''' <param name="mediaIds">List of media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetBulkMediaDataAsync(ByVal mediaIds As IEnumerable(Of Integer), ByVal languageId As Integer, ByVal thumbnailSize As SearchThumbnailSize, ByVal userState As Object) Implements IPartnerService.GetBulkMediaDataAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Media))("GetBulkMediaData",
                                                                        RequestUrlHelper.GetBulkMediaDataUrl(mediaIds, languageId, thumbnailSize))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetBulkMediaDataUrl(mediaIds, languageId, thumbnailSize),
                                                   AddressOf GetBulkMediaDataAsyncCallback,
                                                   New Tuple(Of IEnumerable(Of Integer), Integer, SearchThumbnailSize, Object)(mediaIds, languageId, thumbnailSize, userState))
                Else
                    OnGetBulkMediaDataCompleted(New GetBulkMediaDataCompletedEventArgs() With {.Error = Nothing,.Result = True,.Medias = result,.UserState = userState,
                                                                             .MediaIds = mediaIds,.ThumbnailSize = thumbnailSize,.LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetBulkMediaDataCompleted(New GetBulkMediaDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx), .Result = False,
                                                                                               .Medias = Nothing, .UserState = userState, .MediaIds = mediaIds,
                                                                                               .ThumbnailSize = thumbnailSize, .LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        ''' <summary>
        ''' This method return all information about a media in async mode.
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetBulkMediaDataAsync(ByVal mediaId As Integer, ByVal languageId As Integer, ByVal thumbnailSize As SearchThumbnailSize, ByVal userState As Object) Implements IPartnerService.GetBulkMediaDataAsync
            GetBulkMediaDataAsync({mediaId}, languageId, thumbnailSize, userState)
        End Sub

        Private Sub GetBulkMediaDataAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of IEnumerable(Of Integer), Integer, SearchThumbnailSize, Object))
            If ex Is Nothing Then
                Dim arg As GetBulkMediaDataCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = (From k In result.Keys
                                Where TypeOf result(k) Is JsonObject
                                Select Mapper.Map(Of JsonObject, Media)(CType(result(k), JsonObject))).ToList()

                    SetResultInCache(Of IEnumerable(Of Media))("GetBulkMediaData", RequestUrlHelper.GetBulkMediaDataUrl(userTuple.Item1, userTuple.Item2, userTuple.Item3), retval)
                    arg = New GetBulkMediaDataCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item4, .Result = True,
                                                                         .Medias = retval, .MediaIds = userTuple.Item1, .LanguageId = userTuple.Item2,
                                                                         .ThumbnailSize = userTuple.Item3}
                Else
                    arg = New GetBulkMediaDataCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                        .UserState = userTuple.Item4, .Result = False,
                                                                        .Medias = Nothing, .MediaIds = userTuple.Item1,
                                                                        .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3}

                End If
                OnGetBulkMediaDataCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetBulkMediaDataCompleted(New GetBulkMediaDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .UserState = userTuple.Item4, .Result = False,
                                                                                    .Medias = Nothing, .MediaIds = userTuple.Item1,
                                                                                    .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetBulkMediaDataCompleted(ByVal e As EventArgs.GetBulkMediaDataCompletedEventArgs)
            RaiseEvent GetBulkMediaDataCompleted(Me, e)
        End Sub

        ''' <summary>
        ''' Occurs when [get media data completed].
        ''' </summary>
        ''' <remarks></remarks>
        Public Event GetBulkMediaDataCompleted(ByVal sender As Object, ByVal e As GetBulkMediaDataCompletedEventArgs) Implements IPartnerService.GetBulkMediaDataCompleted

#End Region

#Region "GetMediaGalleries"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods return galleries associated to a media. 
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaGalleries(ByVal mediaId As Integer,
                                          ByVal languageId As Integer,
                                          ByVal thumbnailSize As SearchThumbnailSize) As IEnumerable(Of Gallery) Implements IPartnerService.GetMediaGalleries
            Throw New NotSupportedException()
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetMediaGalleries",
                                                                Function()
                                                                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetMediaGalleriesUrl(mediaId, languageId, thumbnailSize))
                                                                    Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                                    Return result
                                                                End Function,
                                                                RequestUrlHelper.GetMediaGalleriesUrl(mediaId, languageId, thumbnailSize))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods return galleries associated to a media in async mode. 
        ''' </summary>
        ''' <param name="mediaId">Media id.</param>
        ''' <param name="languageId">Language Id.</param>
        ''' <param name="thumbnailSize">Thumbnail size.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaGalleriesAsync(ByVal mediaId As Integer,
                                          ByVal languageId As Integer,
                                          ByVal thumbnailSize As SearchThumbnailSize,
                                          ByVal userState As Object) Implements IPartnerService.GetMediaGalleriesAsync
            Throw New NotSupportedException()
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetMediaGalleries",
                                                                        RequestUrlHelper.GetMediaGalleriesUrl(mediaId, languageId, thumbnailSize))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetMediaGalleriesUrl(mediaId, languageId, thumbnailSize),
                                                   AddressOf GetMediaGalleriesAsyncCallback,
                                                   New Tuple(Of Integer, Integer, SearchThumbnailSize, Object)(mediaId, languageId, thumbnailSize, userState))
                Else
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                 .Result = True,
                                                                                                 .Galleries = result,
                                                                                                 .UserState = userState,
                                                                                                 .MediaId = mediaId,
                                                                                                 .ThumbnailSize = thumbnailSize,
                                                                                                 .LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .Result = False,
                                                                                                .Galleries = Nothing,
                                                                                                .UserState = userState,
                                                                                                .MediaId = mediaId,
                                                                                                .ThumbnailSize = thumbnailSize,
                                                                                                .LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaGalleriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Integer, SearchThumbnailSize, Object))
            If ex Is Nothing Then
                Dim arg As GetMediaGalleriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Gallery))(result)
                    SetResultInCache(Of IEnumerable(Of Gallery))("GetMediaGalleries", RequestUrlHelper.GetMediaGalleriesUrl(userTuple.Item1, userTuple.Item2, userTuple.Item3), retval)
                    arg = New GetMediaGalleriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item4, .Result = True,
                                                                          .Galleries = retval, .MediaId = userTuple.Item1,
                                                                          .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3}
                Else
                    arg = New GetMediaGalleriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                        .UserState = userTuple.Item4, .Result = False,
                                                                        .Galleries = Nothing, .MediaId = userTuple.Item1,
                                                                        .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3}

                End If
                OnGetMediaGalleriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaGalleriesCompleted(New GetMediaGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .UserState = userTuple.Item4, .Result = False,
                                                                                                .Galleries = Nothing, .MediaId = userTuple.Item1,
                                                                                                .LanguageId = userTuple.Item2, .ThumbnailSize = userTuple.Item3})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetMediaGalleriesCompleted(ByVal e As EventArgs.GetMediaGalleriesCompletedEventArgs)
            RaiseEvent GetMediaGalleriesCompleted(Me, e)
        End Sub

        Public Event GetMediaGalleriesCompleted(ByVal sender As Object, ByVal e As GetMediaGalleriesCompletedEventArgs) Implements IPartnerService.GetMediaGalleriesCompleted
#End Region

#Region "GetMediaComp"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method returns comp images. 
        ''' Comp images can ONLY be used to evaluate the image as to suitability for a project, obtain client or internal company approvals, or experiment with layout alternatives. 
        ''' </summary>
        ''' <param name="mediaId">Media ID (ID of the Media whose you want to purchase a license).</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaComp(ByVal mediaId As Integer) As Image Implements IPartnerService.GetMediaComp
            Dim retVal As Image = Nothing
            Try
                retVal = ExecuteQuery(Of Image)("GetMediaComp",
                                                Function()
                                                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetMediaCompUrl(mediaId))
                                                    Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                    Return result
                                                End Function,
                                                RequestUrlHelper.GetMediaCompUrl(mediaId))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This method returns comp images in async mode. 
        ''' Comp images can ONLY be used to evaluate the image as to suitability for a project, obtain client or internal company approvals, or experiment with layout alternatives. 
        ''' </summary>
        ''' <param name="mediaId">Media ID (ID of the Media whose you want to purchase a license).</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaCompAsync(ByVal mediaId As Integer, ByVal userState As Object) Implements IPartnerService.GetMediaCompAsync
            Try
                Dim result = GetResultFromCache(Of Image)("GetMediaComp",
                                                                        RequestUrlHelper.GetMediaCompUrl(mediaId))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetMediaCompUrl(mediaId),
                                                   AddressOf GetMediaCompAsyncCallback,
                                                   New Tuple(Of Integer, Object)(mediaId, userState))
                Else
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = Nothing,
                                                                                                 .Result = True,
                                                                                                 .Image = result,
                                                                                                 .UserState = userState,
                                                                                                 .MediaId = mediaId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .Result = False,
                                                                                                .Image = Nothing,
                                                                                                .UserState = userState,
                                                                                                .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaCompAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Object))
            If ex Is Nothing Then
                Dim arg As GetMediaCompCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, Image)(result)
                    SetResultInCache(Of Image)("GetMediaComp", RequestUrlHelper.GetMediaCompUrl(userTuple.Item1), retval)
                    arg = New GetMediaCompCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                          .Image = retval, .MediaId = userTuple.Item1}
                Else
                    arg = New GetMediaCompCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                        .UserState = userTuple.Item2, .Result = False,
                                                                        .Image = Nothing, .MediaId = userTuple.Item1}

                End If
                OnGetMediaCompCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaCompCompleted(New GetMediaCompCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .UserState = userTuple.Item2, .Result = False,
                                                                                                .Image = Nothing, .MediaId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetMediaCompCompleted(ByVal e As EventArgs.GetMediaCompCompletedEventArgs)
            RaiseEvent GetMediaCompCompleted(Me, e)
        End Sub

        Public Event GetMediaCompCompleted(ByVal sender As Object, ByVal e As GetMediaCompCompletedEventArgs) Implements IPartnerService.GetMediaCompCompleted
#End Region

#Region "GetMediaCompFromMediaUrl"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method retive the bytes array from a Media Comp url.
        ''' </summary>
        ''' <param name="url">Media Comp url.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetMediaCompFromMediaUrl(url As String) As Byte() Implements IPartnerService.GetMediaCompFromMediaUrl
            Dim retVal() As Byte = Nothing
            Try
                retVal = GetResultFromCache(Of Byte())("GetMediaCompFromMediaUrl", url)
                If retVal Is Nothing Then
                    retVal = Me._Requester.GetResponseBytes(url)
                    Dim str = (From c In retVal Select Char.ConvertFromUtf32(c)).Take(20).Aggregate(Function(a, b) a + b)
                    If str.ToLower.StartsWith("bad") Then
                        Throw New FotoliaException(FotoliaErrorMessages.GetMessageByErrorCode("101")) With {.Code = "101"}
                    End If
                    SetResultInCache(Of Byte())("GetMediaCompFromMediaUrl", url, retVal)
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' This method retive the bytes array from a Media Comp url in async mode. 
        ''' </summary>
        ''' <param name="url">Media Comp url.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetMediaCompFromMediaUrlAsync(ByVal url As String, ByVal userState As Object) Implements IPartnerService.GetMediaCompFromMediaUrlAsync
            Try
                Dim result = GetResultFromCache(Of Byte())("GetMediaCompFromMediaUrl", url)
                If result Is Nothing Then
                    Me._Requester.GetResponseBytesAsync(url, AddressOf GetMediaCompFromMediaUrlAsyncCallback, New Tuple(Of String, Object)(url, userState))
                Else
                    OnGetMediaCompFromMediaUrlCompleted(New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = Nothing,
                                                                                                               .Result = True,
                                                                                                               .ImageArray = result,
                                                                                                               .Url = url,
                                                                                                               .UserState = userState})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaCompFromMediaUrlCompleted(New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                               .Result = False,
                                                                                                               .ImageArray = Nothing,
                                                                                                               .Url = url,
                                                                                                               .UserState = userState})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetMediaCompFromMediaUrlAsyncCallback(responseArray() As Byte, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Object))
            If ex Is Nothing Then
                Dim arg As GetMediaCompFromMediaUrlCompletedEventArgs
                If responseArray IsNot Nothing Then
#If SILVERLIGHT = 0 Then
                    Dim str = (From c In responseArray Select Char.ConvertFromUtf32(c)).Take(20).Aggregate(Function(a, b) a + b)
                    If str.ToLower.StartsWith("bad") Then
#Else
                    If responseArray.Length >= 3 AndAlso (responseArray(0) = 66 And responseArray(1) = 97 And responseArray(2) = 100) Then
#End If
                        arg = New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = New [Error]() With {.Code = "101", .Message = FotoliaErrorMessages.GetMessageByErrorCode("101")},
                                                                                     .UserState = userTuple.Item2,
                                                                                     .Result = False,
                                                                                     .ImageArray = Nothing,
                                                                                     .Url = userTuple.Item1}
                    Else
                        SetResultInCache(Of Byte())("GetMediaCompFromMediaUrl", userTuple.Item1, responseArray)
                        arg = New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = Nothing,
                                                                                     .UserState = userTuple.Item2,
                                                                                     .Result = True,
                                                                                     .ImageArray = responseArray,
                                                                                     .Url = userTuple.Item1}
                    End If
            Else
                arg = New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                             .UserState = userTuple.Item2,
                                                                             .Result = False,
                                                                             .ImageArray = Nothing,
                                                                             .Url = userTuple.Item1}

            End If
                OnGetMediaCompFromMediaUrlCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetMediaCompFromMediaUrlCompleted(New GetMediaCompFromMediaUrlCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                               .Result = False,
                                                                                                               .UserState = userTuple.Item2,
                                                                                                               .ImageArray = Nothing,
                                                                                                               .Url = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetMediaCompFromMediaUrlCompleted(ByVal e As EventArgs.GetMediaCompFromMediaUrlCompletedEventArgs)
            RaiseEvent GetMediaCompFromMediaUrlCompleted(Me, e)
        End Sub

        Public Event GetMediaCompFromMediaUrlCompleted(ByVal sender As Object, ByVal e As GetMediaCompFromMediaUrlCompletedEventArgs) Implements IPartnerService.GetMediaCompFromMediaUrlCompleted

#End Region

#Region "GetHomePageImages"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Gets the home page images.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetHomePageImages(ByVal languageId As Integer) As IEnumerable(Of HomeImage) Implements IPartnerService.GetHomePageImages
            Dim retVal As IEnumerable(Of HomeImage) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of HomeImage))("GetHomePageImages",
                                                                Function()
                                                                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetHomePageImagesUrl(languageId))
                                                                    Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                                    Return result
                                                                End Function,
                                                                RequestUrlHelper.GetHomePageImagesUrl(languageId))
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Gets the home page images async.
        ''' </summary>
        ''' <param name="languageId">The language id.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks></remarks>
        Public Sub GetHomePageImagesAsync(ByVal languageId As Integer, ByVal userState As Object) Implements IPartnerService.GetHomePageImagesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of HomeImage))("GetHomePageImages",
                                                                        RequestUrlHelper.GetHomePageImagesUrl(languageId))
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetHomePageImagesUrl(languageId),
                                                   AddressOf GetHomePageImagesAsyncCallback,
                                                   New Tuple(Of Integer, Object)(languageId, userState))
                Else
                    OnGetHomePageImagesCompleted(New GetHomePageImagesCompletedEventArgs() With {.Error = Nothing,.Result = True,.Images = result,
                                                                                                 .UserState = userState,.LanguageId = languageId})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetHomePageImagesCompleted(New GetHomePageImagesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),.Result = False,
                                                                                                .Images = Nothing,.UserState = userState,.LanguageId = languageId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetHomePageImagesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of Integer, Object))
            If ex Is Nothing Then
                Dim arg As GetHomePageImagesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of HomeImage))(result)
                    SetResultInCache(Of IEnumerable(Of HomeImage))("GetHomePageImages", RequestUrlHelper.GetHomePageImagesUrl(userTuple.Item1), retval)
                    arg = New GetHomePageImagesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                          .Images = retval, .LanguageId = userTuple.Item1}
                Else
                    arg = New GetHomePageImagesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                        .UserState = userTuple.Item2, .Result = False, .LanguageId = userTuple.Item1, .Images = Nothing}

                End If
                OnGetHomePageImagesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetHomePageImagesCompleted(New GetHomePageImagesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .UserState = userTuple.Item2, .Result = False,
                                                                                                .Images = Nothing, .LanguageId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetHomePageImagesCompleted(ByVal e As EventArgs.GetHomePageImagesCompletedEventArgs)
            RaiseEvent GetHomePageImagesCompleted(Me, e)
        End Sub

        Public Event GetHomePageImagesCompleted(ByVal sender As Object, ByVal e As GetHomePageImagesCompletedEventArgs) Implements IPartnerService.GetHomePageImagesCompleted

#End Region

#Region "LoginUser"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This method allows you to create an authenticated session to be able to use methods which need authentication.
        ''' If the user is autenticated, the method returns true, otherwise the method returns false.
        ''' The class that implements this interface must manage the user session and the session id.
        ''' </summary>
        ''' <param name="username">User Login.</param>
        ''' <param name="password">User Password.</param>
        ''' <returns>The sessionId if the user is autenticated, otherwise Nothing.</returns>
        ''' <remarks></remarks>
        Public Function LoginUser(ByVal username As String, ByVal password As String) As String Implements IPartnerService.LoginUser
            Dim retVal As String = Nothing
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetLoginUserUrl(), Nothing, "POST", RequestPostHelper.GetLoginUserPost(username, password))
                Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                If result.ContainsKey("session_token") Then
                    retVal = result.GetValue(Of String)("session_token")
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This method allows you to create an authenticated session to be able to use methods which need authentication (in async mode).
        ''' The class that implements this interface must manage the user session and the session id.
        ''' </summary>
        ''' <param name="username">User Login.</param>
        ''' <param name="password">User Password.</param>
        ''' <param name="userState">The user state.</param>
        ''' <remarks>When the login operation is completed, event <see cref="FTTK.Services.Interfaces.IPartnerService.LoginUserCompleted">LoginUserCompleted</see> is reaised.</remarks>
        Public Sub LoginUserAsync(ByVal username As String, ByVal password As String, ByVal userState As Object) Implements IPartnerService.LoginUserAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.GetLoginUserUrl,
                                               New Action(Of String, Exception, Object)(AddressOf LoginUserAsyncCallback),
                                               New Tuple(Of String, Object)(username, userState),
                                               "POST", RequestPostHelper.GetLoginUserPost(username, password))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnLoginUserCompleted(New LoginUserCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                 .SessionId = Nothing,
                                                                                 .Result = False,
                                                                                 .UserState = userState,
                                                                                 .Username = username})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub LoginUserAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim arg As LoginUserCompletedEventArgs
                If result.ContainsKey("session_token") Then
                    Dim sessionId = result.GetValue(Of String)("session_token")
                    arg = New LoginUserCompletedEventArgs() With {.Error = Nothing,
                                                                  .UserState = userTuple.Item2,
                                                                  .Result = Not String.IsNullOrEmpty(sessionId),
                                                                  .SessionId = sessionId,
                                                                  .Username = userTuple.Item1}
                Else
                    arg = New LoginUserCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                  .UserState = userTuple.Item2,
                                                                  .Result = False,
                                                                  .SessionId = Nothing,
                                                                  .Username = userTuple.Item1}
                End If
                OnLoginUserCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnLoginUserCompleted(New LoginUserCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                 .UserState = userTuple.Item2,
                                                                                .Result = False,
                                                                                .SessionId = Nothing,
                                                                                .Username = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnLoginUserCompleted(ByVal e As EventArgs.LoginUserCompletedEventArgs)
            RaiseEvent LoginUserCompleted(Me, e)
        End Sub

        Public Event LoginUserCompleted(ByVal sender As Object, ByVal e As LoginUserCompletedEventArgs) Implements IPartnerService.LoginUserCompleted
#End Region

#Region "GetUserData"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods return data for logged user.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserData(ByVal sessionId As String) As UserData Implements IPartnerService.GetUserData
            Dim retVal As UserData = Nothing
            Try
                retVal = ExecuteQuery(Of UserData)("GetUserData",
                                                    Function()
                                                        Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetUserDataUrl(), sessionId)
                                                        Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                        Return result
                                                    End Function,
                                                    RequestUrlHelper.GetUserDataUrl())
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods return data for logged user (in async mode).
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserDataAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserDataAsync
            Try
                Dim result = GetResultFromCache(Of UserData)("GetUserData", RequestUrlHelper.GetUserDataUrl(), sessionId)
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetUserDataUrl(),
                                                   sessionId,
                                                   AddressOf GetUserDataAsyncCallback,
                                                   New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .SessionId = sessionId,
                                                                                    .UserState = userState,
                                                                                    .UserData = result})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .Result = False,
                                                                                    .SessionId = sessionId,
                                                                                    .UserState = userState,
                                                                                    .UserData = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserDataAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Object))
            If ex Is Nothing Then
                Dim arg As GetUserDataCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, UserData)(result)
                    SetResultInCache(Of UserData)("GetUserData", RequestUrlHelper.GetUserDataUrl(), userTuple.Item1, retval)
                    arg = New GetUserDataCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                    .UserData = retval, .SessionId = userTuple.Item1}
                Else
                    arg = New GetUserDataCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                    .UserData = Nothing, .SessionId = userTuple.Item1}

                End If
                OnGetUserDataCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserDataCompleted(New GetUserDataCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                                    .UserData = Nothing, .SessionId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetUserDataCompleted(ByVal e As EventArgs.GetUserDataCompletedEventArgs)
            RaiseEvent GetUserDataCompleted(Me, e)
        End Sub

        Public Event GetUserDataCompleted(ByVal sender As Object, ByVal e As GetUserDataCompletedEventArgs) Implements IPartnerService.GetUserDataCompleted
#End Region

#Region "GetUserStats"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods returns statistics for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserStats(ByVal sessionId As String) As UserStats Implements IPartnerService.GetUserStats
            Dim retVal As UserStats = Nothing
            Try
                retVal = ExecuteQuery(Of UserStats)("GetUserStats",
                                                    Function()
                                                        Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetUserStatsUrl(), sessionId)
                                                        Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                                                        Return result
                                                    End Function,
                                                    RequestUrlHelper.GetUserStatsUrl())
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods returns statistics for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserStatsAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserStatsAsync
            Try
                Dim result = GetResultFromCache(Of UserStats)("GetUserStats", RequestUrlHelper.GetUserDataUrl(), sessionId)
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetUserStatsUrl(),
                                                   sessionId,
                                                   AddressOf GetUserStatsAsyncCallback,
                                                   New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = Nothing,
                                                                                    .Result = True,
                                                                                    .SessionId = sessionId,
                                                                                    .UserState = userState,
                                                                                    .UserStats = result})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .Result = False,
                                                                                    .SessionId = sessionId,
                                                                                    .UserState = userState,
                                                                                    .UserStats = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserStatsAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Object))
            If ex Is Nothing Then
                Dim arg As GetUserStatsCompletedEventArgs
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of JsonObject, UserStats)(result)
                    SetResultInCache(Of UserStats)("GetUserStats", RequestUrlHelper.GetUserDataUrl(), userTuple.Item1, retval)
                    arg = New GetUserStatsCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                    .UserStats = retval, .SessionId = userTuple.Item1}
                Else
                    arg = New GetUserStatsCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                    .UserStats = Nothing, .SessionId = userTuple.Item1}

                End If
                OnGetUserStatsCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserStatsCompleted(New GetUserStatsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                                    .UserStats = Nothing, .SessionId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetUserStatsCompleted(ByVal e As EventArgs.GetUserStatsCompletedEventArgs)
            RaiseEvent GetUserStatsCompleted(Me, e)
        End Sub

        Public Event GetUserStatsCompleted(ByVal sender As Object, ByVal e As GetUserStatsCompletedEventArgs) Implements IPartnerService.GetUserStatsCompleted
#End Region

#Region "GetUserGalleries"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods return private galleries for logged user. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function GetUserGalleries(ByVal sessionId As String) As IEnumerable(Of Gallery) Implements IPartnerService.GetUserGalleries
            Dim retVal As IEnumerable(Of Gallery) = Nothing
            Try
                retVal = ExecuteQuery(Of IEnumerable(Of Gallery))("GetUserGalleries",
                                                    Function()
                                                        Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetUserGalleriesUrl(), sessionId)
                                                        Dim result = _JsonParser.ParseIntoArrayObjects(resultStr)
                                                        Return result
                                                    End Function,
                                                    RequestUrlHelper.GetUserGalleriesUrl())
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' This methods return private galleries for logged user in async mode.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Sub GetUserGalleriesAsync(ByVal sessionId As String, ByVal userState As Object) Implements IPartnerService.GetUserGalleriesAsync
            Try
                Dim result = GetResultFromCache(Of IEnumerable(Of Gallery))("GetUserGalleries", RequestUrlHelper.GetUserGalleriesUrl(), sessionId)
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetUserGalleriesUrl(),
                                                   sessionId,
                                                   AddressOf GetUserGalleriesAsyncCallback,
                                                   New Tuple(Of String, Object)(sessionId, userState))
                Else
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = Nothing,
                                                                                                .Result = True,
                                                                                                .SessionId = sessionId,
                                                                                                .UserState = userState,
                                                                                                .Galleries = result})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                .Result = False,
                                                                                                .SessionId = sessionId,
                                                                                                .UserState = userState,
                                                                                                .Galleries = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserGalleriesAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Object))
            If ex Is Nothing Then
                Dim arg As GetUserGalleriesCompletedEventArgs
                Dim result = _JsonParser.ParseIntoArrayObjects(responseString)
                If result IsNot Nothing Then
                    Dim retval = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Gallery))(result)
                    SetResultInCache(Of IEnumerable(Of Gallery))("GetUserGalleries", RequestUrlHelper.GetUserGalleriesUrl(), userTuple.Item1, retval)
                    arg = New GetUserGalleriesCompletedEventArgs() With {.Error = Nothing, .UserState = userTuple.Item2, .Result = True,
                                                                    .Galleries = retval, .SessionId = userTuple.Item1}
                Else
                    arg = New GetUserGalleriesCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                    .Galleries = Nothing, .SessionId = userTuple.Item1}

                End If
                OnGetUserGalleriesCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserGalleriesCompleted(New GetUserGalleriesCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                    .UserState = userTuple.Item2, .Result = False,
                                                                                    .Galleries = Nothing, .SessionId = userTuple.Item1})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetUserGalleriesCompleted(ByVal e As EventArgs.GetUserGalleriesCompletedEventArgs)
            RaiseEvent GetUserGalleriesCompleted(Me, e)
        End Sub

        Public Event GetUserGalleriesCompleted(ByVal sender As Object, ByVal e As GetUserGalleriesCompletedEventArgs) Implements IPartnerService.GetUserGalleriesCompleted
#End Region

#Region "GetUserGalleryMedias"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods allows to search media in logged user galleries or lightbox. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="galleryId">The gallery id. If not id sent, retrieve the content of the logged user Lightbox.</param>
        ''' <param name="numberOfResults">The total number of results.</param>
        ''' <param name="pageNumber">Page number to display.</param>
        ''' <param name="mediaPerPage">Maximum number of media returned. Valid values: 1 to 64.</param>
        ''' <param name="thumbnailSize">Size of the thumbnail.</param>
        ''' <param name="detailLevel">The detail level.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserGalleryMedias(ByVal sessionId As String,
                                             ByVal galleryId As String,
                                             ByRef numberOfResults As Integer,
                                             Optional pageNumber As Integer = 1,
                                             Optional mediaPerPage As Integer = 32,
                                             Optional thumbnailSize As SearchThumbnailSize = SearchThumbnailSize.Size110,
                                             Optional detailLevel As SearchDetailLevel = SearchDetailLevel.Base) As IEnumerable(Of Media) Implements IPartnerService.GetUserGalleryMedias
            Dim retVal As IEnumerable(Of Media) = Nothing
            Try
                Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias",
                                                                                                 RequestUrlHelper.GetUserGalleryMediasUrl(pageNumber, mediaPerPage, thumbnailSize, galleryId, detailLevel),
                                                                                                 sessionId)
                If cacheValue IsNot Nothing Then
                    retVal = cacheValue.Item1
                    numberOfResults = cacheValue.Item2
                End If

                If retVal Is Nothing Then
                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetUserGalleryMediasUrl(pageNumber, mediaPerPage, thumbnailSize, galleryId, detailLevel), sessionId)
                    Dim completeResult = _JsonParser.ParseIntoSingleObject(resultStr)
                    numberOfResults = completeResult.GetValue(Of Integer)("nb_results", -1)
                    Dim mediaJsonObjects = (From v In completeResult.Values.OfType(Of JsonObject)()
                                            Select v).ToList()

                    retVal = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Media))(mediaJsonObjects)

                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias",
                                                                                  RequestUrlHelper.GetUserGalleryMediasUrl(pageNumber, mediaPerPage, thumbnailSize, galleryId, detailLevel),
                                                                                  sessionId,
                                                                                  New Tuple(Of IEnumerable(Of Media), Integer)(retVal, numberOfResults))
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods allows to search media in logged user galleries or lightbox. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="galleryId">The gallery id. If not id sent, retrieve the content of the logged user Lightbox.</param>
        ''' <param name="pageNumber">Page number to display.</param>
        ''' <param name="mediaPerPage">Maximum number of media returned. Valid values: 1 to 64.</param>
        ''' <param name="thumbnailSize">Size of the thumbnail.</param>
        ''' <param name="detailLevel">The detail level.</param>
        ''' <remarks></remarks>
        Public Sub GetUserGalleryMediasAsync(ByVal sessionId As String,
                                             ByVal galleryId As String,
                                             ByVal userState As Object,
                                             Optional pageNumber As Integer = 1,
                                             Optional mediaPerPage As Integer = 32,
                                             Optional thumbnailSize As SearchThumbnailSize = SearchThumbnailSize.Size110,
                                             Optional detailLevel As SearchDetailLevel = SearchDetailLevel.Base) Implements IPartnerService.GetUserGalleryMediasAsync
            Try
                Dim result As IEnumerable(Of Media) = Nothing
                Dim numberOfResults As Integer
                Dim cacheValue = GetResultFromCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias",
                                                                                                 RequestUrlHelper.GetUserGalleryMediasUrl(pageNumber, mediaPerPage, thumbnailSize, galleryId, detailLevel),
                                                                                                 sessionId)
                If cacheValue IsNot Nothing Then
                    result = cacheValue.Item1
                    numberOfResults = cacheValue.Item2
                End If
                If result Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetUserGalleryMediasUrl(pageNumber, mediaPerPage, thumbnailSize, galleryId, detailLevel),
                                                   sessionId,
                                                   AddressOf GetUserGalleryMediasAsyncCallback,
                                                   New Tuple(Of String, String, Integer, Integer, SearchThumbnailSize, SearchDetailLevel, Object)(sessionId, galleryId, pageNumber, mediaPerPage, thumbnailSize, detailLevel, userState))
                Else
                    OnGetSearchResultsCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = Nothing, .Result = True, .MediaList = result, .UserState = userState,
                                                                                                   .NumberOfResults = numberOfResults, .DetailLevel = detailLevel, .MediaPerPage = mediaPerPage,
                                                                                                   .PageNumber = pageNumber, .SessionId = sessionId, .ThumbnailSize = thumbnailSize})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSearchResultsCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                   .Result = False, .MediaList = Nothing, .UserState = userState,
                                                                                                   .NumberOfResults = -1, .DetailLevel = detailLevel, .MediaPerPage = mediaPerPage,
                                                                                                   .PageNumber = pageNumber, .SessionId = sessionId, .ThumbnailSize = thumbnailSize})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserGalleryMediasAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, String, Integer, Integer, SearchThumbnailSize, SearchDetailLevel, Object))
            If ex Is Nothing Then
                Dim arg As GetUserGalleryMediasCompletedEventArgs

                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                If result IsNot Nothing Then
                    Dim numberOfResults = result.GetValue(Of Integer)("nb_results", -1)
                    Dim mediaJsonObjects = From v In result.Values.OfType(Of JsonObject)()
                                            Select v

                    Dim mediaList = Mapper.Map(Of IEnumerable(Of JsonObject), IEnumerable(Of Media))(mediaJsonObjects).ToList()

                    SetResultInCache(Of Tuple(Of IEnumerable(Of Media), Integer))("GetUserGalleryMedias",
                                                                                  RequestUrlHelper.GetUserGalleryMediasUrl(userTuple.Item3, userTuple.Item4, userTuple.Item5, userTuple.Item2, userTuple.Item6),
                                                                                  userTuple.Item1,
                                                                                  New Tuple(Of IEnumerable(Of Media), Integer)(mediaList, numberOfResults))

                    arg = New GetUserGalleryMediasCompletedEventArgs() With {.Error = Nothing, .Result = True, .MediaList = mediaList, .UserState = userTuple.Item7,
                                                                                .NumberOfResults = numberOfResults, .DetailLevel = userTuple.Item6, .MediaPerPage = userTuple.Item4,
                                                                                .PageNumber = userTuple.Item3, .SessionId = userTuple.Item1, .ThumbnailSize = userTuple.Item5}
                Else
                    arg = New GetUserGalleryMediasCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                             .Result = False, .MediaList = Nothing, .UserState = userTuple.Item7,
                                                                             .NumberOfResults = -1, .DetailLevel = userTuple.Item6, .MediaPerPage = userTuple.Item4,
                                                                             .PageNumber = userTuple.Item3, .SessionId = userTuple.Item1, .ThumbnailSize = userTuple.Item5}

                End If
                OnGetSearchResultsCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetSearchResultsCompleted(New GetUserGalleryMediasCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                   .Result = False, .MediaList = Nothing, .UserState = userTuple.Item7,
                                                                                                   .NumberOfResults = -1, .DetailLevel = userTuple.Item6, .MediaPerPage = userTuple.Item4,
                                                                                                   .PageNumber = userTuple.Item3, .SessionId = userTuple.Item1, .ThumbnailSize = userTuple.Item5})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetSearchResultsCompleted(ByVal e As EventArgs.GetUserGalleryMediasCompletedEventArgs)
            RaiseEvent GetUserGalleryMediasCompleted(Me, e)
        End Sub

        Public Event GetUserGalleryMediasCompleted(ByVal sender As Object, ByVal e As GetUserGalleryMediasCompletedEventArgs) Implements IPartnerService.GetUserGalleryMediasCompleted
#End Region

#Region "CreateUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Creates a new user gallery.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryName">Name of the gallery.</param>
        ''' <returns>The method returns the gallery id or nothing if gallery isn't created.</returns>
        ''' <remarks></remarks>
        Public Function CreateUserGallery(ByVal sessionId As String, ByVal galleryName As String) As String Implements IPartnerService.CreateUserGallery
            Dim retVal As String = Nothing
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.CreateUserGalleryUrl(), sessionId, "POST", RequestPostHelper.CreateUserGalleryPost(galleryName))
                Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                If result.ContainsKey("id") Then
                    retVal = result.GetValue(Of String)("id")
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Creates the user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryName">Name of the gallery.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub CreateUserGalleryAsync(ByVal sessionId As String,
                                          ByVal galleryName As String,
                                          ByVal userState As Object) Implements IPartnerService.CreateUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.CreateUserGalleryUrl,
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf CreateUserGalleryAsyncCallback),
                                               New Tuple(Of String, String, Object)(sessionId, galleryName, userState),
                                               "POST", RequestPostHelper.CreateUserGalleryPost(galleryName))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnCreateUserGalleryCompleted(New CreateUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                 .SessionId = sessionId,
                                                                                                 .Result = False,
                                                                                                 .UserState = userState,
                                                                                                 .GalleryName = galleryName,
                                                                                                 .GalleryId = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub CreateUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, String, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim arg As CreateUserGalleryCompletedEventArgs
                If result.ContainsKey("id") Then
                    Dim galleryId = result.GetValue(Of String)("id")
                    arg = New CreateUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                          .SessionId = userTuple.Item1,
                                                                          .UserState = userTuple.Item3,
                                                                          .Result = Not String.IsNullOrEmpty(galleryId),
                                                                          .GalleryId = galleryId,
                                                                          .GalleryName = userTuple.Item2}
                Else
                    arg = New CreateUserGalleryCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                          .SessionId = userTuple.Item1,
                                                                          .UserState = userTuple.Item3,
                                                                          .Result = False,
                                                                          .GalleryId = Nothing,
                                                                          .GalleryName = userTuple.Item2}
                End If
                OnCreateUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnCreateUserGalleryCompleted(New CreateUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                 .SessionId = userTuple.Item1,
                                                                                                 .UserState = userTuple.Item3,
                                                                                                 .Result = False,
                                                                                                 .GalleryId = Nothing,
                                                                                                 .GalleryName = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnCreateUserGalleryCompleted(ByVal e As EventArgs.CreateUserGalleryCompletedEventArgs)
            RaiseEvent CreateUserGalleryCompleted(Me, e)
        End Sub

        Public Event CreateUserGalleryCompleted(ByVal sender As Object, ByVal e As CreateUserGalleryCompletedEventArgs) Implements IPartnerService.CreateUserGalleryCompleted
#End Region

#Region "DeleteUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Deletes the user gallery.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryId">Id of the gallery to delete.</param>
        ''' <returns>TRUE if the gallery is deleted, otherwise FALSE.</returns>
        ''' <remarks></remarks>
        Public Function DeleteUserGallery(ByVal sessionId As String, ByVal galleryId As String) As Boolean Implements IPartnerService.DeleteUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.DeleteUserGalleryUrl(), sessionId, "POST", RequestPostHelper.DeleteUserGalleryPost(galleryId))
                Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                If result.ContainsKey("deleteUserGallery") Then
                    retVal = String.Compare(result.GetValue(Of String)("deleteUserGallery"), "success", True) = 0
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Deletes the user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="galleryId">Id of the gallery to delete.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub DeleteUserGalleryAsync(ByVal sessionId As String,
                                          ByVal galleryId As String,
                                          ByVal userState As Object) Implements IPartnerService.DeleteUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.DeleteUserGalleryUrl(),
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf DeleteUserGalleryAsyncCallback),
                                               New Tuple(Of String, String, Object)(sessionId, galleryId, userState),
                                               "POST", RequestPostHelper.DeleteUserGalleryPost(galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnDeleteUserGalleryCompleted(New DeleteUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                 .SessionId = sessionId,
                                                                                                 .Result = False,
                                                                                                 .UserState = userState,
                                                                                                 .GalleryId = galleryId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub DeleteUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, String, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim arg As DeleteUserGalleryCompletedEventArgs
                If result.ContainsKey("deleteUserGallery") Then
                    arg = New DeleteUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                          .SessionId = userTuple.Item1,
                                                                          .UserState = userTuple.Item3,
                                                                          .Result = String.Compare(result.GetValue(Of String)("deleteUserGallery"), "success", StringComparison.InvariantCultureIgnoreCase) = 0,
                                                                          .GalleryId = userTuple.Item2}
                Else
                    arg = New DeleteUserGalleryCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                          .SessionId = userTuple.Item1,
                                                                          .UserState = userTuple.Item3,
                                                                          .Result = False,
                                                                          .GalleryId = userTuple.Item2}
                End If
                OnDeleteUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnDeleteUserGalleryCompleted(New DeleteUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                 .SessionId = userTuple.Item1,
                                                                                                 .UserState = userTuple.Item3,
                                                                                                 .Result = False,
                                                                                                 .GalleryId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnDeleteUserGalleryCompleted(ByVal e As EventArgs.DeleteUserGalleryCompletedEventArgs)
            RaiseEvent DeleteUserGalleryCompleted(Me, e)
        End Sub

        Public Event DeleteUserGalleryCompleted(ByVal sender As Object, ByVal e As DeleteUserGalleryCompletedEventArgs) Implements IPartnerService.DeleteUserGalleryCompleted
#End Region

#Region "AddToUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods allows you to add a content to your default lightbox or any of your existing galleries.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <returns><c>true</c> if media is added correctly, otherwise <c>false.</c></returns>
        ''' <remarks></remarks>
        Public Function AddToUserGallery(ByVal sessionId As String,
                                         ByVal mediaId As Integer,
                                         ByVal galleryId As String) As Boolean Implements IPartnerService.AddToUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.AddToUserGalleryUrl(), sessionId, "POST", RequestPostHelper.AddToUserGalleryPost(mediaId, galleryId))
                Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                If result.ContainsKey("addtousergallery") Then
                    retVal = String.Compare(result.GetValue(Of String)("addtousergallery"), "success", True) = 0
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' This methods allows you to add a content to your default lightbox or any of your existing galleries.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub AddToUserGalleryAsync(ByVal sessionId As String,
                                         ByVal mediaId As Integer,
                                         ByVal galleryId As String,
                                         ByVal userState As Object) Implements IPartnerService.AddToUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.AddToUserGalleryUrl,
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf AddToUserGalleryAsyncCallback),
                                               New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState),
                                               "POST", RequestPostHelper.AddToUserGalleryPost(mediaId, galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnAddToUserGalleryCompleted(New AddToUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                               .SessionId = sessionId,
                                                                                               .Result = False,
                                                                                               .UserState = userState,
                                                                                               .GalleryId = galleryId,
                                                                                               .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub AddToUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Integer, String, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim arg As AddToUserGalleryCompletedEventArgs
                If result.ContainsKey("addtousergallery") Then
                    arg = New AddToUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                          .SessionId = userTuple.Item1,
                                                                          .UserState = userTuple.Item4,
                                                                          .Result = String.Compare(result.GetValue(Of String)("addtousergallery"), "success", StringComparison.InvariantCultureIgnoreCase) = 0,
                                                                          .GalleryId = userTuple.Item3,
                                                                         .MediaId = userTuple.Item2}
                Else
                    arg = New AddToUserGalleryCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                         .SessionId = userTuple.Item1,
                                                                         .UserState = userTuple.Item4,
                                                                         .Result = False,
                                                                         .GalleryId = userTuple.Item3,
                                                                         .MediaId = userTuple.Item2}
                End If
                OnAddToUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnAddToUserGalleryCompleted(New AddToUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                               .SessionId = userTuple.Item1,
                                                                                               .UserState = userTuple.Item4,
                                                                                               .Result = False,
                                                                                               .GalleryId = userTuple.Item3,
                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnAddToUserGalleryCompleted(ByVal e As EventArgs.AddToUserGalleryCompletedEventArgs)
            RaiseEvent AddToUserGalleryCompleted(Me, e)
        End Sub

        Public Event AddToUserGalleryCompleted(ByVal sender As Object, ByVal e As AddToUserGalleryCompletedEventArgs) Implements IPartnerService.AddToUserGalleryCompleted

#End Region

#Region "RemoveFromUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' This methods allows you to remove a content from your default lightbox or any of your existing galleries. 
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function RemoveFromUserGallery(ByVal sessionId As String,
                                              ByVal mediaId As Integer,
                                              ByVal galleryId As String) As Boolean Implements IPartnerService.RemoveFromUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.RemoveFromUserGalleryUrl(), sessionId, "POST", RequestPostHelper.RemoveFromUserGalleryPost(mediaId, galleryId))
                Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                If result.ContainsKey("removefromusergallery") Then
                    retVal = String.Compare(result.GetValue(Of String)("removefromusergallery"), "success", True) = 0
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods allows you to remove a content from your default lightbox or any of your existing galleries async.
        ''' </summary>
        ''' <param name="sessionId">The session id.</param>
        ''' <param name="mediaId">The media id.</param>
        ''' <param name="galleryId">The gallery id.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub RemoveFromUserGalleryAsync(ByVal sessionId As String,
                                              ByVal mediaId As Integer,
                                              ByVal galleryId As String,
                                              ByVal userState As Object) Implements IPartnerService.RemoveFromUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.RemoveFromUserGalleryUrl,
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf RemoveFromUserGalleryAsyncCallback),
                                               New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState),
                                               "POST", RequestPostHelper.RemoveFromUserGalleryPost(mediaId, galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnRemoveFromUserGalleryCompleted(New RemoveFromUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                       .SessionId = sessionId,
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub RemoveFromUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Integer, String, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim arg As RemoveFromUserGalleryCompletedEventArgs
                If result.ContainsKey("removefromusergallery") Then
                    arg = New RemoveFromUserGalleryCompletedEventArgs() With {.Error = Nothing,
                                                                              .SessionId = userTuple.Item1,
                                                                              .UserState = userTuple.Item4,
                                                                              .Result = String.Compare(result.GetValue(Of String)("removefromusergallery"), "success", StringComparison.InvariantCultureIgnoreCase) = 0,
                                                                              .GalleryId = userTuple.Item3,
                                                                              .MediaId = userTuple.Item2}
                Else
                    arg = New RemoveFromUserGalleryCompletedEventArgs() With {.Error = New [Error]() With {.Code = "", .Message = FotoliaErrorMessages.GetDefaultMessage()},
                                                                             .SessionId = userTuple.Item1,
                                                                             .UserState = userTuple.Item4,
                                                                             .Result = False,
                                                                             .GalleryId = userTuple.Item3,
                                                                             .MediaId = userTuple.Item2}
                End If
                OnRemoveFromUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnRemoveFromUserGalleryCompleted(New RemoveFromUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                       .SessionId = userTuple.Item1,
                                                                                                       .UserState = userTuple.Item4,
                                                                                                       .Result = False,
                                                                                                       .GalleryId = userTuple.Item3,
                                                                                                       .MediaId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnRemoveFromUserGalleryCompleted(ByVal e As EventArgs.RemoveFromUserGalleryCompletedEventArgs)
            RaiseEvent RemoveFromUserGalleryCompleted(Me, e)
        End Sub

        Public Event RemoveFromUserGalleryCompleted(ByVal sender As Object, ByVal e As RemoveFromUserGalleryCompletedEventArgs) Implements IPartnerService.RemoveFromUserGalleryCompleted
#End Region

#Region "GetUserAdvancedStats"
#If SILVERLIGHT = 0 Then

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="period">Valid values for simple date statistics.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserAdvancedStats(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal period As UserStatsDatePeriod) As UserAdvancedStats Implements IPartnerService.GetUserAdvancedStats
            Return GetUserAdvancedStats(sessionId, type, range, period, Nothing, Nothing)
        End Function

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="startDate">The start date.</param>
        ''' <param name="endDate">The end date.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function GetUserAdvancedStats(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal startDate As Date,
                                             ByVal endDate As Date) As UserAdvancedStats Implements IPartnerService.GetUserAdvancedStats
            Return GetUserAdvancedStats(sessionId, type, range, Nothing, startDate, endDate)
        End Function

        Private Function GetUserAdvancedStats(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal period As UserStatsDatePeriod?,
                                             ByVal startDate As Date?,
                                             ByVal endDate As Date?) As UserAdvancedStats
            Contract.Requires(Of ArgumentException)(Not String.IsNullOrEmpty(sessionId), "SessionId must be not null")
            Dim retVal As UserAdvancedStats = Nothing
            Try
                retVal = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats", RequestUrlHelper.GetUserAdvancedStatsUrl(type, range, period, startDate, endDate), sessionId)
                If retVal Is Nothing Then
                    Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.GetUserAdvancedStatsUrl(type, range, period, startDate, endDate), sessionId)
                    Dim result = _JsonParser.ParseIntoSingleObject(resultStr)
                    retVal = Mapper.Map(Of Tuple(Of JsonObject, Entities.UserStatsType, Entities.UserStatsTimeRange), Entities.UserAdvancedStats) _
                        (New Tuple(Of JsonObject, Entities.UserStatsType, Entities.UserStatsTimeRange)(result, type, range))

                    SetResultInCache(Of UserAdvancedStats)("GetUserAdvancedStats",
                                                           RequestUrlHelper.GetUserAdvancedStatsUrl(type, range, period, startDate, endDate),
                                                           sessionId, retVal)
                End If
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account (in async mode). 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="period">Valid values for simple date statistics.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetUserAdvancedStatsAsync(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal period As UserStatsDatePeriod,
                                             ByVal userState As Object) Implements IPartnerService.GetUserAdvancedStatsAsync
            GetUserAdvancedStatsAsync(sessionId, type, range, period, Nothing, Nothing, userState)
        End Sub

        ''' <summary>
        ''' This methods allows you to get sales/views/income statistics from your account. 
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="type">Type of data to retrieve.</param>
        ''' <param name="range">Group by clause.</param>
        ''' <param name="startDate">The start date.</param>
        ''' <param name="endDate">The end date.</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub GetUserAdvancedStatsAsync(ByVal sessionId As String,
                                             ByVal type As UserStatsType,
                                             ByVal range As UserStatsTimeRange,
                                             ByVal startDate As Date,
                                             ByVal endDate As Date,
                                             ByVal userState As Object) Implements IPartnerService.GetUserAdvancedStatsAsync
            GetUserAdvancedStatsAsync(sessionId, type, range, Nothing, startDate, endDate, userState)
        End Sub

        Private Sub GetUserAdvancedStatsAsync(ByVal sessionId As String,
                                            ByVal type As UserStatsType,
                                            ByVal range As UserStatsTimeRange,
                                            ByVal period As UserStatsDatePeriod?,
                                            ByVal startDate As Date?,
                                            ByVal endDate As Date?,
                                            ByVal userState As Object)
            Try
                Dim retval = GetResultFromCache(Of UserAdvancedStats)("GetUserAdvancedStats",
                                                                      RequestUrlHelper.GetUserAdvancedStatsUrl(type, range, period, startDate, endDate),
                                                                      sessionId)
                If retval Is Nothing Then
                    Me._Requester.GetResponseAsync(RequestUrlHelper.GetUserAdvancedStatsUrl(type, range, period, startDate, endDate),
                                                   sessionId,
                                                   AddressOf GetUserAdvancedStatsAsyncCallback,
                                                   New Tuple(Of String, UserStatsType, UserStatsTimeRange, UserStatsDatePeriod?, Date?, Date?, Object) _
                                                        (sessionId, type, range, period, startDate, endDate, userState))
                Else
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Nothing, .Result = True, .UserState = userState,
                                                                                                       .EndDate = endDate, .Period = period, .Range = range,
                                                                                                       .SessionId = sessionId, .StartDate = startDate, .Type = type, .UserStats = retval})
                End If
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                       .Result = False, .UserState = userState, .EndDate = endDate,
                                                                                                       .Period = period, .Range = range, .SessionId = sessionId,
                                                                                                       .StartDate = startDate, .Type = type, .UserStats = Nothing})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub GetUserAdvancedStatsAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, UserStatsType, UserStatsTimeRange, UserStatsDatePeriod?, Date?, Date?, Object))
            If ex Is Nothing Then
                Dim result = _JsonParser.ParseIntoSingleObject(responseString)
                Dim retVal = Mapper.Map(Of Tuple(Of JsonObject, Entities.UserStatsType, Entities.UserStatsTimeRange), Entities.UserAdvancedStats) _
                                (New Tuple(Of JsonObject, Entities.UserStatsType, Entities.UserStatsTimeRange)(result, userTuple.Item2, userTuple.Item3))

                SetResultInCache(Of UserAdvancedStats)("GetUserAdvancedStats",
                                                       RequestUrlHelper.GetUserAdvancedStatsUrl(userTuple.Item2, userTuple.Item3, userTuple.Item4, userTuple.Item5, userTuple.Item6),
                                                       userTuple.Item1, retVal)
                Dim arg = New GetUserAdvancedStatsCompletedEventArgs() With {.Error = Nothing, .Result = True, .UserState = userTuple.Item7,
                                                                             .EndDate = userTuple.Item6, .Period = userTuple.Item4, .Range = userTuple.Item3,
                                                                             .SessionId = userTuple.Item1, .StartDate = userTuple.Item5,
                                                                             .Type = userTuple.Item2, .UserStats = retVal}
                OnGetUserAdvancedStatsCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnGetUserAdvancedStatsCompleted(New GetUserAdvancedStatsCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                       .Result = False, .UserState = userTuple.Item7,
                                                                                                       .EndDate = userTuple.Item6, .Period = userTuple.Item4,
                                                                                                       .Range = userTuple.Item3, .SessionId = userTuple.Item1,
                                                                                                       .StartDate = userTuple.Item5, .Type = userTuple.Item2,
                                                                                                       .UserStats = Nothing})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnGetUserAdvancedStatsCompleted(ByVal e As EventArgs.GetUserAdvancedStatsCompletedEventArgs)
            RaiseEvent GetUserAdvancedStatsCompleted(Me, e)
        End Sub

        Public Event GetUserAdvancedStatsCompleted(ByVal sender As Object, ByVal e As GetUserAdvancedStatsCompletedEventArgs) Implements IPartnerService.GetUserAdvancedStatsCompleted
#End Region

#Region "MoveUpMediaInUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Move a media up in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveUpMediaInUserGallery(ByVal sessionId As String,
                                                 ByVal mediaId As Integer,
                                                 ByVal galleryId As String) As Boolean Implements IPartnerService.MoveUpMediaInUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.MoveUpMediaInUserGalleryUrl(), sessionId, "POST", RequestPostHelper.MoveUpMediaInUserGalleryPost(mediaId, galleryId))
                retVal = True
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If

        ''' <summary>
        ''' Moves up media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveUpMediaInUserGalleryAsync(ByVal sessionId As String,
                                                 ByVal mediaId As Integer,
                                                 ByVal galleryId As String,
                                                 ByVal userState As Object) Implements IPartnerService.MoveUpMediaInUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.MoveUpMediaInUserGalleryUrl(),
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf MoveUpMediaInUserGalleryAsyncCallback),
                                               New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState),
                                               "POST", RequestPostHelper.MoveUpMediaInUserGalleryPost(mediaId, galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveUpMediaInUserGalleryCompleted(New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                       .SessionId = sessionId,
                                                                                                       .Result = False,
                                                                                                       .UserState = userState,
                                                                                                       .GalleryId = galleryId,
                                                                                                       .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveUpMediaInUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Integer, String, Object))
            If ex Is Nothing Then
                Dim arg = New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = Nothing, .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                  .Result = True, .GalleryId = userTuple.Item3, .MediaId = userTuple.Item2}
                OnMoveUpMediaInUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveUpMediaInUserGalleryCompleted(New MoveUpMediaInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                               .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                                               .Result = False, .GalleryId = userTuple.Item3,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnMoveUpMediaInUserGalleryCompleted(ByVal e As EventArgs.MoveUpMediaInUserGalleryCompletedEventArgs)
            RaiseEvent MoveUpMediaInUserGalleryCompleted(Me, e)
        End Sub

        Public Event MoveUpMediaInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveUpMediaInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveUpMediaInUserGalleryCompleted
#End Region

#Region "MoveDownMediaInUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Move a media down in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveDownMediaInUserGallery(ByVal sessionId As String,
                                                   ByVal mediaId As Integer,
                                                   ByVal galleryId As String) As Boolean Implements IPartnerService.MoveDownMediaInUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.MoveDownMediaInUserGalleryUrl(),
                                                          sessionId,
                                                          "POST",
                                                          RequestPostHelper.MoveDownMediaInUserGalleryPost(mediaId, galleryId))
                retVal = True
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' Moves down media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveDownMediaInUserGalleryAsync(ByVal sessionId As String,
                                                   ByVal mediaId As Integer,
                                                   ByVal galleryId As String,
                                                   ByVal userState As Object) Implements IPartnerService.MoveDownMediaInUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.MoveDownMediaInUserGalleryUrl(),
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf MoveDownMediaInUserGalleryAsyncCallback),
                                               New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState),
                                               "POST", RequestPostHelper.MoveDownMediaInUserGalleryPost(mediaId, galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveDownMediaInUserGalleryCompleted(New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                                   .SessionId = sessionId,
                                                                                                                   .Result = False,
                                                                                                                   .UserState = userState,
                                                                                                                   .GalleryId = galleryId,
                                                                                                                   .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveDownMediaInUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Integer, String, Object))
            If ex Is Nothing Then
                Dim arg = New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = Nothing, .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                  .Result = True, .GalleryId = userTuple.Item3, .MediaId = userTuple.Item2}
                OnMoveDownMediaInUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveDownMediaInUserGalleryCompleted(New MoveDownMediaInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                               .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                                               .Result = False, .GalleryId = userTuple.Item3,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnMoveDownMediaInUserGalleryCompleted(ByVal e As EventArgs.MoveDownMediaInUserGalleryCompletedEventArgs)
            RaiseEvent MoveDownMediaInUserGalleryCompleted(Me, e)
        End Sub

        Public Event MoveDownMediaInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveDownMediaInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveDownMediaInUserGalleryCompleted
#End Region

#Region "MoveMediaToTopInUserGallery"
#If SILVERLIGHT = 0 Then
        ''' <summary>
        ''' Move a media to top in an user gallery.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <returns></returns>
        ''' <remarks>This method requires authentication with a valid session token.</remarks>
        Public Function MoveMediaToTopInUserGallery(ByVal sessionId As String,
                                                    ByVal mediaId As Integer,
                                                    ByVal galleryId As String) As Boolean Implements IPartnerService.MoveMediaToTopInUserGallery
            Dim retVal As Boolean = False
            Try
                Dim resultStr = Me._Requester.GetResponse(RequestUrlHelper.MoveMediaToTopInUserGalleryUrl(),
                                                          sessionId,
                                                          "POST",
                                                          RequestPostHelper.MoveMediaToTopInUserGalleryPost(mediaId, galleryId))
                retVal = True
            Catch ex As Exception
                ManageException(ex)
            End Try
            Return retVal
        End Function
#End If
        ''' <summary>
        ''' Moves to top media in user gallery async.
        ''' </summary>
        ''' <param name="sessionId">The user session id.</param>
        ''' <param name="mediaId">Existing media ID.</param>
        ''' <param name="galleryId">User gallery ID ID. If empty the default user gallery will be used</param>
        ''' <param name="userState">The user state object.</param>
        ''' <remarks></remarks>
        Public Sub MoveMediaToTopInUserGalleryAsync(ByVal sessionId As String,
                                                    ByVal mediaId As Integer,
                                                    ByVal galleryId As String,
                                                    ByVal userState As Object) Implements IPartnerService.MoveMediaToTopInUserGalleryAsync
            Try
                Me._Requester.GetResponseAsync(RequestUrlHelper.MoveMediaToTopInUserGalleryUrl(),
                                               sessionId,
                                               New Action(Of String, Exception, Object)(AddressOf MoveMediaToTopInUserGalleryAsyncCallback),
                                               New Tuple(Of String, Integer, String, Object)(sessionId, mediaId, galleryId, userState),
                                               "POST", RequestPostHelper.MoveMediaToTopInUserGalleryPost(mediaId, galleryId))
            Catch ex As Exception
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveMediaToTopInUserGalleryCompleted(New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                                   .SessionId = sessionId,
                                                                                                                   .Result = False,
                                                                                                                   .UserState = userState,
                                                                                                                   .GalleryId = galleryId,
                                                                                                                   .MediaId = mediaId})
                Else
                    Throw
                End If
            End Try
        End Sub

        Private Sub MoveMediaToTopInUserGalleryAsyncCallback(responseString As String, ex As Exception, stateObject As Object)
            Dim userTuple = CType(stateObject, Tuple(Of String, Integer, String, Object))
            If ex Is Nothing Then
                Dim arg = New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = Nothing, .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                  .Result = True, .GalleryId = userTuple.Item3, .MediaId = userTuple.Item2}
                OnMoveMediaToTopInUserGalleryCompleted(arg)
            Else
                If TypeOf ex Is WebException Then
                    Dim webEx = CType(ex, WebException)
                    OnMoveMediaToTopInUserGalleryCompleted(New MoveMediaToTopInUserGalleryCompletedEventArgs() With {.Error = CreateErrorFromWebException(webEx),
                                                                                                               .SessionId = userTuple.Item1, .UserState = userTuple.Item4,
                                                                                                               .Result = False, .GalleryId = userTuple.Item3,
                                                                                                               .MediaId = userTuple.Item2})
                Else
                    Throw ex
                End If
            End If
        End Sub

        Protected Sub OnMoveMediaToTopInUserGalleryCompleted(ByVal e As EventArgs.MoveMediaToTopInUserGalleryCompletedEventArgs)
            RaiseEvent MoveMediaToTopInUserGalleryCompleted(Me, e)
        End Sub

        Public Event MoveMediaToTopInUserGalleryCompleted(ByVal sender As Object, ByVal e As MoveMediaToTopInUserGalleryCompletedEventArgs) Implements IPartnerService.MoveMediaToTopInUserGalleryCompleted
#End Region
    End Class
End Namespace